package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class UpLoadController {
    @Autowired
    private HttpServletResponse response;
    @Value("${img.name}")
    private String url;

    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String s = UUID.randomUUID().toString();
        String s1 = s + substring;
        file.transferTo(new File(url + s1));
        return R.success(s1);
    }

    @GetMapping("/download")
    public void download(String name) throws IOException {
        FileInputStream is = new FileInputStream(new File(url + name));
        ServletOutputStream os = response.getOutputStream();
        byte[] bytes = new byte[1024];
        while (true) {
            int len = is.read(bytes);
            if (len==-1){
                break;
            }
            os.write(bytes,0,len);
        }
        os.close();
        is.close();
    }
}
